import type { App } from 'vue';
import {
  type RouterHistory,
  createMemoryHistory,
  createRouter,
  createWebHashHistory,
  createWebHistory
} from 'vue-router';
import { createBuiltinVueRoutes } from './routes/builtin';
import { createRouterGuard } from './guard';

// 读取环境变量，决定路由模式
const { VITE_ROUTER_HISTORY_MODE = 'history', VITE_BASE_URL } = import.meta.env;

// 路由历史模式映射表
const historyCreatorMap: Record<Env.RouterHistoryMode, (base?: string) => RouterHistory> = {
  hash: createWebHashHistory,
  history: createWebHistory,
  memory: createMemoryHistory
};

// 创建路由实例
export const router = createRouter({
  history: historyCreatorMap[VITE_ROUTER_HISTORY_MODE](VITE_BASE_URL), // 根据环境变量选择路由模式
  routes: createBuiltinVueRoutes() // 加载内置路由
});

// 路由初始化函数，挂载路由守卫
export async function setupRouter(app: App) {
  app.use(router); // 挂载到 Vue 应用
  createRouterGuard(router); // 注册路由守卫
  await router.isReady(); // 等待路由准备好
}
